package com.app.shortvideo.net.base

import android.text.TextUtils
import com.app.shortvideo.MApplication
import com.blankj.utilcode.util.GsonUtils
import com.blankj.utilcode.util.LogUtils
import okhttp3.*
import okio.Buffer
import java.io.IOException
import java.net.URLDecoder

class HttpLogInterceptor(tag: String, private val showLog: Boolean) : Interceptor {
    private val tag: String = "HTTP#$tag"

    @Throws(IOException::class)
    override fun intercept(chain: Interceptor.Chain): Response {
        val request = chain.request()
        if (showLog) {
            logForRequest(request)
        }
        val response = chain.proceed(request)
        return logForResponse(response)
    }

    private fun logForResponse(response: Response): Response {
        try {
            if (showLog) {
                LogUtils.d(tag, "********响应日志开始********")
                val sb = StringBuffer()
                val builder = response.newBuilder()
                val clone = builder.build()
                sb.append("url : ${clone.request.url}")
                sb.append("\ncode : ${clone.code}")
                if (!TextUtils.isEmpty(clone.message)) {
                    sb.append("\nmessage : ${clone.message}")
                }
                var body = clone.body
                if (body != null) {
                    val mediaType = body.contentType()
                    if (mediaType != null) {
                        if (isText(mediaType)) {
                            val resp = body.string()
                            sb.append("\n响应内容 : $resp")
                            LogUtils.d(tag, sb.toString())
                            LogUtils.d(tag, "********响应日志结束********")
                            body = ResponseBody.create(mediaType, resp)
                            val response = response.newBuilder().body(body).build()
                            /**
                             * 拦截强制更新(用通知的方式，是为了避免数据报错)
                             */
                            responseVersion(response)
                            return response
                        } else {
                            LogUtils.d(tag, "响应内容 : " + " 发生错误")
                        }
                    }
                }
                LogUtils.d(tag, "********响应日志结束********")
            }
        } catch (e: Exception) {
            e.printStackTrace();
        }
        return response
    }
    private fun responseVersion(response: Response) {
        val jsonString = ResponseUtils.getResponseString(response)
        val bodyGson = GsonUtils.fromJson(jsonString, BaseResponseBean::class.java)
        if (bodyGson.isMastUpdate) {//强制更新！
            val versionResponse = GsonUtils.fromJson(jsonString, VersionBaseResponse::class.java)
            MApplication.mInstance.getCurrentActivity()?.let {
                it.runOnUiThread {
//                    UpdateDialog(it, versionResponse.data).newInstance()?.showDialog()
                }
            }
        }
    }
    private fun logForRequest(request: Request) {
        try {
            val url = request.url.toString()
            LogUtils.d(tag, "========请求日志开始=======")
            val sb = StringBuffer()
            sb.append("请求方式 : " + request.method)
            sb.append("\nurl : $url")
            val requestBody = request.body
            sb.append("\n请求头= " + request.headers.toString())
            if (requestBody != null) {
                val mediaType = requestBody.contentType()
                if (mediaType != null) {
                    sb.append("\n请求内容类别 : $mediaType")
                    if (isText(mediaType)) {
                        sb.append("\n请求内容 : " + bodyToString(request))
                    } else {
                        sb.append("\n请求内容 : " + " 无法识别。")
                    }
                }
            }
            LogUtils.d(tag, sb.toString())
            LogUtils.d(tag, "========请求日志结束=======")
        } catch (e: Exception) {
        }
    }

    private fun isText(mediaType: MediaType): Boolean {
        return (mediaType.type == "text" || (mediaType.subtype == "json" || mediaType.subtype == "xml" || mediaType.subtype == "html" || mediaType.subtype == "webviewhtml" || mediaType.subtype == "x-www-form-urlencoded"))
    }

    private fun bodyToString(request: Request): String {
        return try {
            val copy = request.newBuilder().build()
            val buffer = Buffer()
            if (null != copy.body) copy.body!!.writeTo(buffer)
            val message = buffer.readUtf8()
            URLDecoder.decode(message, "utf-8")
        } catch (e: IOException) {
            "在解析请求内容时候发生了异常"
        }
    }

}